2015-10-19 3 views
1

Я хочу получить доступ к свойствам веб-страницы (название, метаописание, URL, изображение по умолчанию и т. Д.), Когда пользователь открывает расширение Share на iOS, используя файл javascript. Я использую следующий код для JavaScript (https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW12):Доступ к свойствам веб-страницы в расширении Share

var MyExtensionJavaScriptClass = function() {}; 

MyExtensionJavaScriptClass.prototype = { 
    run: function(arguments) { 
    // Pass the baseURI of the webpage to the extension. 
     arguments.completionFunction({"url": document.baseURI}); 
     arguments.completionFunction({"host": getHost()}); 
     arguments.completionFunction({"title": document.title}); 
     arguments.completionFunction({"description": getDescription()}); 
     arguments.completionFunction({"image": getImage()}); 
    }, 
    getHost: function() { 
     var l = document.createElement("a"); 
     l.href = href; 
     return l.hostname; 
    }, 
    getDescription: function() { 
     var metas = document.getElementsByTagName('meta'); 

     for (i=0; i<metas.length; i++) { 
      if (metas[i].getAttribute("property") == "description") { 
      return metas[i].getAttribute("content"); 
      } 
     } 
     return ""; 
    }, 
    getImage: function() { 
     // Need to find this out 
     return ""; 
    }, 
// Note that the finalize function is only available in iOS. 
    finalize: function(arguments) { 
     // arguments contains the value the extension provides in [NSExtensionContext completeRequestReturningItems:completion:]. 
    // In this example, the extension provides a color as a returning item. 
    document.body.style.backgroundColor = arguments["bgColor"]; 
    } 
}; 

// The JavaScript file must contain a global object named "ExtensionPreprocessingJS". 
var ExtensionPreprocessingJS = new MyExtensionJavaScriptClass; 

Является ли это правильный путь для доступа к свойствам веб-страниц, и то, что это лучший способ, чтобы принести первое изображение в содержании.

Любая помощь будет высоко оценена.

ответ

7

Вот как я решил эту проблему.

JS код:

var MyExtensionJavaScriptClass = function() {}; 

MyExtensionJavaScriptClass.prototype = { 
    getDescription: function() { 
     var metas = document.getElementsByTagName('meta'); 
     for (i=0; i<metas.length; i++) { 
      if (metas[i].getAttribute("name") == "description") { 
       return metas[i].getAttribute("content"); 
      } 
     } 
     return ""; 
    }, 
    getImage: function() { 
     var metas = document.getElementsByTagName('meta'); 
     for (i=0; i<metas.length; i++) { 
      if (metas[i].getAttribute("name") == "og:image" || metas[i].getAttribute("name") == "sailthru.image.full" || metas[i].getAttribute("name") == "twitter:image:src") { 
       return metas[i].getAttribute("content"); 
      } 
     } 
     return ""; 
    }, 
    run: function(arguments) { 
    // Pass the baseURI of the webpage to the extension. 
     arguments.completionFunction({"url": document.baseURI, "host": document.location.hostname, "title": document.title, "description": this.getDescription(), "image": this.getImage()}); 
    }, 
// Note that the finalize function is only available in iOS. 
    finalize: function(arguments) { 
     // arguments contains the value the extension provides in [NSExtensionContext completeRequestReturningItems:completion:]. 
    // In this example, the extension provides a color as a returning item. 
    // document.body.style.backgroundColor = arguments["bgColor"]; 
    } 
}; 

// The JavaScript file must contain a global object named "ExtensionPreprocessingJS". 
var ExtensionPreprocessingJS = new MyExtensionJavaScriptClass; 

// ExtensionPreprocessingJS.test(); 

Swift Code:

for item: AnyObject in (self.extensionContext?.inputItems)! { 
    let inputItem = item as! NSExtensionItem 

    for provider: AnyObject in inputItem.attachments! { 
     let itemProvider = provider as! NSItemProvider 

     if itemProvider.hasItemConformingToTypeIdentifier(kUTTypePropertyList as String) { 
      itemProvider.loadItemForTypeIdentifier(kUTTypePropertyList as String, options: nil, completionHandler: { (result: NSSecureCoding?, error: NSError!) -> Void in 
       if let resultDict = result as? NSDictionary { 
        self.articleTitle = resultDict[NSExtensionJavaScriptPreprocessingResultsKey]!["title"] as! String 
        self.articleHost = resultDict[NSExtensionJavaScriptPreprocessingResultsKey]!["host"] as! String 
        self.articleDesc = resultDict[NSExtensionJavaScriptPreprocessingResultsKey]!["description"] as! String 
        self.articleImage = resultDict[NSExtensionJavaScriptPreprocessingResultsKey]!["image"] as! String 
        self.articleUrl = resultDict[NSExtensionJavaScriptPreprocessingResultsKey]!["url"] as! String 
       } 
      }) 
     } 
    } 
} 
+0

Ваш JS не работает для изображения .. –

+0

Я имею в виду METAS [я] .getAttribute ("имя") == «ог : изображение "не возвращает изображение. –

+0

@AsadullahAli Целью этого условия является проверка того, включены ли в URL-адреса открытые графические теги или карты sailthru или twitter. Если теги присутствуют, выберите изображение. Для этого кода может потребоваться некоторое обновление на основе URL-адреса, который вы тестируете. Можете ли вы поделиться URL-адресом, который вы тестируете? – Puru

Смежные вопросы